<?php
	class Pay extends MY_controller{
		function __construct(){
			error_reporting(E_ALL ^ E_NOTICE);
			parent::__construct();
		}

		function wx_notify(){

			$order_log['status'] = ''; //接受通知成功
			$order_log['pay_type'] = '';
			$order_log['order_id'] = '';
			$order_log['order_detail'] = '';
			// $order_log['add_time'] = time();
			$this->db->insert("o2o_school_pay_logs", $order_log);

			ini_set('date.timezone', 'Asia/Shanghai');
	        $xml = file_get_contents("php://input");
	        libxml_disable_entity_loader(true);
	        $wx_order = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
	        if(empty($wx_order)){
	        	echo '缺少数据';exit;
	        }
	        /*if(!$wx_order){
	        	$wx_order = json_decode('{"appid":"wx0071d459ab95ac0f","attach":"48","bank_type":"CFT","cash_fee":"1","fee_type":"CNY","is_subscribe":"Y","mch_id":"1312419001","nonce_str":"8rfb0wlqkjg9as6puednzi3yv4co7h5t","openid":"oGDMhwfERAFsInLWei5GEEUocVkU","out_trade_no":"48","result_code":"SUCCESS","return_code":"SUCCESS","sign":"80693B5716AFE3A0AFAEACA5525B464C","time_end":"20170420110427","total_fee":"1","trade_type":"NATIVE","transaction_id":"4003522001201704207659086900"}', true);
	        }*/
	        $order_log['status'] = 1; //接受通知成功
			$order_log['pay_type'] = 1;
			$order_log['order_id'] = $wx_order['out_trade_no'];
			$order_log['order_detail'] = json_encode($wx_order);
			// $order_log['add_time'] = time();
			$this->db->insert("o2o_school_pay_logs", $order_log);

			$wx_config_data = $order_info = array();



	        if(!empty($wx_order)){
	        	$order_info = get_field_by_where("shopping_orders", "*", "order_id='{$wx_order['out_trade_no']}'");
	        	if(empty($order_info)){
					//查询不到订单，不用再继续发送了
					echo '查询不到订单';
					exit;
				}

	        	$wx_config_data = get_field_by_where("o2o_school_wx_config", "*", "school_id='{$order_info['school_id']}'");
				$wx_config['appid'] = $wx_config_data['app_id'];
			    $wx_config['mch_id'] = $wx_config_data['mch_id'];
			    $wx_config['apikey'] = $wx_config_data['apikey'];
			    $wx_config['sslcertPath'] = $wx_config_data['apiclient_cert'];
			    $wx_config['sslkeyPath'] = $wx_config_data['apiclient_key'];
			    $wx_config['notify_url'] = $this->config->item("wx_pay_notify_url");
			    require_once 'third_party/wxpayApi/wxpay.php';
		        $weixin_pay = new wxpay($wx_config);
	        }

	        if ($order_info['order_status'] == 1) {
				echo '订单已经支付过';
	            $weixin_pay->response_back("SUCCESS"); //回复微信服务器，通知成功，已经支付，业务已经更新，停止通知。
	            exit();
	        }

	        if(!$wx_config_data || empty($wx_order)){
	        	echo '微信配置不存在或者微信POST数据为空';
		    	$weixin_pay->response_back("FAIL");	//该学校暂时未配置微信支付，回复微信继续发送通知
		    	exit;
		    }

		    //检查通信是否成功；签名是否成功；签名校验是否成功
	        if ($wx_order == null or $wx_order['return_code'] == 'FAIL' || !$weixin_pay->validate($wx_order)) {
	        	echo '签名验证失败';
	            $weixin_pay->response_back("FAIL"); //回复微信服务器，通知失败，继续发通知。
	            exit();
	        }

	        $order_log['status']       = 2; //2、验证成功
	        // $order_log['add_time']     = time();
	        $this->db->insert("o2o_school_pay_logs", $order_log);

	        $wx_order_total_fee = round($wx_order['total_fee'] / 100, 2); //将微信订单付款总金额转换为 元
	        if ($wx_order['result_code'] == 'SUCCESS' && $wx_order['time_end'] != '' /*&& $order_info['total_order_amount'] == $wx_order_total_fee*/) {
	            //记录订单操作数据库日志
	            $order_log['status']   = 3; //3、付款成功
	            // $order_log['add_time'] = time();
	            $this->db->insert("o2o_school_pay_logs", $order_log);

	            $order_data['payment_method']  = 1;	//支付方式（1：微信支付，2：支付宝）
	            $order_data['payment_status']  = 2; //支付状态：0未支付1支付中2支付成功3支付失败
	            $order_data['payment_time']    = strtotime($wx_order['time_end']); //付款时间
	            $order_data['payment_on']      = $wx_order['transaction_id']; //第三方支付交易号
	            $order_data['payment_money_amount']     = $wx_order['total_fee'] / 100; //实付金额
	            $order_data['buyer_account']   = $wx_order['openid']; //微信openid
	            $order_data['order_detail']    = json_encode($wx_order);
	            $order_data['order_status']    = 1;

	            $this->db->update('shopping_orders', $order_data, array('order_id' => $wx_order['out_trade_no']));
				$weixin_pay->response_back("SUCCESS"); //回复微信服务器，通知成功，支付成功，停止通知。
				exit();
	        } else {
	        	echo '订单验证失败';
	            $weixin_pay->response_back("FAIL"); //回复微信服务器，未支付，继续发通知。
	        }
		}
	}